package cn.yunhe.servlet;

import cn.yunhe.biz.NewsService;
import cn.yunhe.pojo.News;
import cn.yunhe.pojo.Page;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/ToMainServlet")
public class ToMainServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword=request.getParameter("keyword");
        NewsService newsService=new NewsService();
        //得到当前页
        String currPage = request.getParameter("pageIndex");
        //如果当前页为空,那么就是首页 currPage=1
        if (currPage ==null){
            currPage="1";
        }
        int pageIndex=Integer.parseInt(currPage);
        //总条数
        int newsCount = newsService.getNewsCount(keyword);
        int totalPages =PageUtil.getTotalPages(newsCount,PageUtil.newsPageSize);

        if (pageIndex<1){
            pageIndex=1;
        }
        if (pageIndex>totalPages){
            pageIndex=totalPages;
        }

        //根据当前页和每页条数,赋值给Page的属性
        Page page = new Page();
        page.setStartPage(PageUtil.newsPageSize*(pageIndex-1));
        page.setEndPage(PageUtil.newsPageSize);
        page.setKeyword(keyword);

        //得到分页的List
        List<News> newsList=newsService.getNewsByPage(page);
        //将List放在request当中
        HttpSession session=request.getSession();
        session.setAttribute("keyword",keyword);

        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("totalPages",totalPages);
        request.setAttribute("newsList",newsList);
        //跳转到主页
        request.getRequestDispatcher("main.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
